package com.scut.fy.admin.service.impl;

import com.google.code.kaptcha.Producer;
import com.scut.fy.admin.model.dto.ImageCodeDto;
import com.scut.fy.admin.service.ImageCodeService;
import com.scut.fy.common.core.constant.FyConstant;
import com.scut.fy.common.core.util.Assert;
import com.scut.fy.common.web.model.HttpResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author JY
 * @version 1.0
 * @date 2021/8/25
 */
@Service
public class ImageCodeServiceImpl implements ImageCodeService {

    private static final Logger log = LoggerFactory.getLogger(ImageCodeServiceImpl.class);
    @Resource
    private Producer producer;

    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public ImageCodeDto createImageCode(String randomStr) {
        Assert.isBlank(randomStr, "随机码不能为空");
        try {
            // 生成文字验证码
            final String text = producer.createText();
            // 生成图片验证码
            final BufferedImage image = producer.createImage(text);
            // 文字验证码存到redis里面
            redisTemplate.opsForValue().set(
                    FyConstant.DEFAULT_CODE_KEY + randomStr,
                    text,
                    FyConstant.DEFAULT_IMAGE_EXPIRE,
                    TimeUnit.SECONDS);
            // 图片验证码报文返回
            return new ImageCodeDto(text, image);
        } catch (Exception e) {
            log.error("创建验证码失败", e);
            return null;
        }
    }

    @Override
    public HttpResult<Boolean> checkImageCode(String randomStr, String codeStr) {
        HttpResult<Boolean> httpResult = new HttpResult<Boolean>();
        if (StringUtils.isEmpty(randomStr) || StringUtils.isEmpty(codeStr)) {
            httpResult.setCode(HttpResult.BAD_REQUEST);
            httpResult.setMsg("randomStr或者codeStr不能为空");
            httpResult.setData(false);
            return httpResult;
        }
        String code = redisTemplate.opsForValue()
                .get(FyConstant.DEFAULT_CODE_KEY + randomStr).toString();
        if (StringUtils.isEmpty(code)) {
            httpResult.setCode(HttpResult.BAD_REQUEST);
            httpResult.setMsg("没有对应的验证码或者验证码已过期");
            httpResult.setData(false);
            return httpResult;
        }
        if (codeStr.equals(code)) {
            httpResult.setCode(HttpResult.OK);
            httpResult.setMsg("验证码通过校验");
            httpResult.setData(true);
        } else {
            httpResult.setCode(HttpResult.BAD_REQUEST);
            httpResult.setMsg("验证码不通过校验");
            httpResult.setData(false);
        }
        return httpResult;
    }
}
